<?php
/**
 * @Author:      zk
 * @DateTime:    18-6-21 下午1:30
 * @Description: PMS 供应商管理相关
 */
class PMSSupplierNewController extends BaseController {
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-21 下午1:36
     * @Description:     供应商管理 =》 供应商列表
     * @param string $token             用户token
     * @param string $name              公司名称
     * @param int $contract_status      合同状态    1:未签合同;2:有效;3:无效;4:已延期;
     * @param int $work_together_type   合作状态    1:正常合作;2:暂停合作;3:终止合作;
     * @param int $regular_pay          结款方式    1:月结;0:现金;2:按区域设置;3:按门店设置;
     * @param int $businss_express      物流配送    1:安惠配送;2:供应商配送;3:第三方物流;
     * @param int $tax                  是否含税  (1:含税;2:不含税;)
     * @param int $logistics_freight    物流运费  (1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
     * @param int $page                 页码 [ 默认为1 ]
     * @param int $page_size            每页数据条数 [ 默认为25 ]
     * @link http://api.anhui.com/v1/pms/supplier/supplierList?token=60fccf4c8de5a9fc2f00d072cc89c941
     */
    public function supplierList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'page' => 'integer',
                'page_size' => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $name               = Input::get('name', '');               //公司名称
            $contract_status    = Input::get('contract_status', '');    //合同状态    1:未签合同;2:有效;3:无效;4:已延期;
            $work_together_type = Input::get('work_together_type', ''); //合作状态    1:正常合作;2:暂停合作;3:终止合作;
            $regular_pay        = Input::get('regular_pay', '');        //结款方式    1:月结;0:现金;2:按区域设置;3:按门店设置;
            $businss_express    = Input::get('businss_express', '');    //物流配送    1:安惠配送;2:供应商配送;3:第三方物流;
            $tax                = Input::get('tax', '');                //是否含税  (1:含税;2:不含税;)
            $logistics_freight  = Input::get('logistics_freight', '');  //物流运费  (1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
            $page               = Input::get('page', 1);                //页码 [ 默认为1 ]
            $page_size          = Input::get('page_size', 25);          //每页数据条数 [ 默认为25 ]
            
            $select_arr = [
                'maintenance_supplier.id', 'name', 'contract_status', 'work_together_type', 'regular_pay', 
                'businss_express', 'supplier_class_level', 'tax', 'logistics_freight', 
                'ass_user.id as assId', 'ass_user.user_name as assUserName', 
            ];
            $list = MaintenanceSupplier::select($select_arr)
                    ->orderBy(DB::raw('work_together_type is null'))
                    ->orderBy('work_together_type')
                    ->orderBy(DB::raw('contract_status is null'))
                    ->orderBy('contract_status')
                    ->orderBy('regular_pay', 'desc')
                    ->leftJoin('ass_user', 'ass_user.pms_supplier_id', '=', 'maintenance_supplier.id')
                    ->whereRaw('(ass_user.pms_supplier_id is not null or ass_user.pms_supplier_id is null)');
            if($name != ''){
                $list->where('name', 'like', '%'.$name.'%');
            }
            if($contract_status != ''){
                $list->where('contract_status', $contract_status);
            }
            if($work_together_type != ''){
                $list->where('work_together_type', $work_together_type);
            }
            if($regular_pay != ''){
                $list->where('regular_pay', $regular_pay);
            }
            if($businss_express != ''){
                $list->where('businss_express', $businss_express);
            }
            if($tax != ''){
                $list->where('tax', $tax);
            }
            if($logistics_freight != ''){
                $list->where('logistics_freight', $logistics_freight);
            }
            
            $count = $list->count();
            $list = $list->skip($page_size*($page-1))->take($page_size)->get();
            
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'count' => $count,
                    'list' => $list,
                ],
                'extra' => [
                    'contract_status_arr' => MaintenanceSupplier::$contract_status_arr,
                    'work_together_type_arr' => MaintenanceSupplier::$work_together_type_arr,
                    'regular_pay_arr' => MaintenanceSupplier::$regular_pay_arr,
                    'businss_express_arr' => MaintenanceSupplier::$businss_express_arr,
                    'tax_arr' => MaintenanceSupplier::$tax_arr,
                    'logistics_freight_arr' => MaintenanceSupplier::$logistics_freight_arr,
                ],
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "supplierList", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-21 下午3:28
     * @Description:     修改供应商的合作状态
     * @param string $token             用户token
     * @param int $id                   供应商id
     * @param int $work_together_type   合作状态    1:正常合作;2:暂停合作;3:终止合作;
     * @link http://api.anhui.com/v1/pms/supplier/modifyWorkTogetherType?token=60fccf4c8de5a9fc2f00d072cc89c941&id=1&work_together_type=2
     */
    public function modifyWorkTogetherType() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'work_together_type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id                 = Input::get('id');                 //供应商id
            $work_together_type = Input::get('work_together_type'); //合作状态    1:正常合作;2:暂停合作;3:终止合作;
            
            $ms = MaintenanceSupplier::find($id);
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $old = clone $ms;
            $ms->work_together_type = $work_together_type;
            $ms->purchase_status = $work_together_type==1?1:0;
            try{
                $ms->save();
                
                $model = 'modifyWorkTogetherType';
                $supplier_id = $id;
                $type = 'update';
                $content = '用户：'.$res['user']->id.',更改供应商合作状态，原状态：'.$old->work_together_type.',新状态：'.$work_together_type;
//                $old = $old->work_together_type;
//                $new = $work_together_type;
                $old = json_encode($old);
                $new = json_encode(MaintenanceSupplier::find($id));
                $by = $res['user']->id;
                PmsOpLog::write($model, $supplier_id, $type, $content, $old, $new, $by);
                break;
            }catch (Exception $e) {
                Log::error("error", array("system" => "pms" ,"event" => "modifyWorkTogetherType", "input" =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "modifyWorkTogetherType", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-22 上午11:05
     * @Description:     根据供应商id获取供应商的公司相关信息
     * @param string $token             用户token
     * @param int $id                   供应商id
     * @link http://api.anhui.com/v1/pms/supplier/getSupplierCompanyInfo?token=3f0641ce3dc3ebb51ef49973fd5e1dd7&id=1
     */
    public function getSupplierCompanyInfo() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id = Input::get('id');                 //供应商id
            $select_arr = [
                'id', 'name', 'juridical', 'certify_type', 'certify_num', 'agent', 'postcode', 'operating_address', 
                'work_together_type', 'car_type', 'licence_name', 'licence_credit_num', 'licence_company_type', 
                'licence_juridical', 'licence_created_time', 'licence_home', 'licence_capital', 'licence_term_type', 
                'licence_term_starttime', 'licence_term_endtime', 'scope', 'supplier_class_level',
            ];
            $info = MaintenanceSupplier::select($select_arr)
                    ->where('status', 1)
                    ->where('id', $id)
                    ->first();
            if(!$info){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            
            //附件数组
            $files = [
                'gsjj' => [],   //公司简介
                'cpjs' => [],   //产品介绍
                'yyzzfyj' => [],   //营业执照复印件
                'frsfzfyj' => [],   //法人身份证复印件
            ];
            //获取供应上的附件列表
            $files_list = PMSSupplierFiles::getFilesList($info->id);
            if(!empty($files_list)){
            $url = Config::get('config.pms_supplier_files_url');       //供应商附件目录
                foreach ($files_list as $k => $v) {
                    $temp = [
                        'id' => $v['id'],
                        'file_name' => $v['file_path'],
                        'storage_name' => $v['storage_name'],
                        'file_type' => $v['file_type'],
                        'file_url' => $url.''.$v['storage_name'],
                        'created_at' => $v['created_at'],
                        'created_by' => $v['created_by'],
                    ];
                    switch ($v['type']) {
                        case 'gsjj':
                            $files['gsjj'][] = $temp;
                            break;
                        case 'cpjs':
                            $files['cpjs'][] = $temp;
                            break;
                        case 'yyzzfyj':
                            $files['yyzzfyj'][] = $temp;
                            break;
                        case 'frsfzfyj':
                            $files['frsfzfyj'][] = $temp;
                            break;
                        default:
                            break;
                    }
                }
            }
            
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'info' => $info,
                    'files' => $files,
                ]
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "getSupplierCompanyInfo", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-22 下午3:56
     * @Description:     根据供应商id获取供应商的业务信息相关
     * @param string $token             用户token
     * @param int $id                   供应商id
     * @link http://api.anhui.com/v1/pms/supplier/getSupplierBusinessInfo?token=3f0641ce3dc3ebb51ef49973fd5e1dd7&id=1
     */
    public function getSupplierBusinessInfo() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id = Input::get('id');                 //供应商id
            $select_arr = [
                'id', 'name', 'business_type', 'business_type_comment', 'business_rebate_policy', 'businss_express', 
                'after_sale', 'business_activity', 'business_train', 'logistics_freight',
            ];
            $info = MaintenanceSupplier::select($select_arr)
                    ->where('status', 1)
                    ->where('id', $id)
                    ->first();
            if(!$info){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            
            //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
            if($info->logistics_freight == 3){
                $info->logistics_freight_ext = MaintenanceSupplierLogisticsFreightArea::getAreaList($id);
            }
            if($info->logistics_freight == 4){
                $info->logistics_freight_ext = MaintenanceSupplierLogisticsFreightShop::getShopList($id);
            }
            
            //附件数组
            $files = [
                'ywxx' => [],   //业务信息
                'wlxx' => [],   //物流信息
                'shxx' => [],   //售后信息
                'scxx' => [],   //市场信息
                'pxxx' => [],   //培训信息
            ];
            //获取供应上的附件列表
            $files_list = PMSSupplierFiles::getFilesList($info->id);
            if(!empty($files_list)){
            $url = Config::get('config.pms_supplier_files_url');       //供应商附件目录
                foreach ($files_list as $k => $v) {
                    $temp = [
                        'id' => $v['id'],
                        'file_name' => $v['file_path'],
                        'storage_name' => $v['storage_name'],
                        'file_type' => $v['file_type'],
                        'file_url' => $url.''.$v['storage_name'],
                        'created_at' => $v['created_at'],
                        'created_by' => $v['created_by'],
                    ];
                    switch ($v['type']) {
                        case 'ywxx':
                            $files['ywxx'][] = $temp;
                            break;
                        case 'wlxx':
                            $files['wlxx'][] = $temp;
                            break;
                        case 'shxx':
                            $files['shxx'][] = $temp;
                            break;
                        case 'scxx':
                            $files['scxx'][] = $temp;
                            break;
                        case 'pxxx':
                            $files['pxxx'][] = $temp;
                            break;
                        default:
                            break;
                    }
                }
            }
            
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'info' => $info,
                    'files' => $files,
                ]
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "getSupplierBusinessInfo", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-21 下午5:31
     * @Description:     根据供应商id获取供应商的财务相关信息
     * @param string $token             用户token
     * @param int $id                   供应商id
     * @link http://api.anhui.com/v1/pms/supplier/getSupplierFinanceInfo?token=3f0641ce3dc3ebb51ef49973fd5e1dd7&id=1
     */
    public function getSupplierFinanceInfo() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id = Input::get('id');                 //供应商id
            $select_arr = [
                'id', 'name', 'bank', 'account', 'regular_pay', 'invoice_type', 'invoice_address', 'billing_phone', 
                'taxpayer', 'gather_bank', 'gather_account', 'company_regist_address', 'regular_pay', 'regular_pay_comment', 
                'compare_bill', 'bill_day', 'credit_money', 'licence_credit_num', 'licence_home', 'tax',
            ];
            $info = MaintenanceSupplier::select($select_arr)
                    ->where('status', 1)
                    ->where('id', $id)
                    ->first();
            if(!$info){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            
            //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
            if($info->regular_pay == 2){
                $info->regular_pay_ext = MaintenanceSupplierPayArea::getAreaList($id);
            }
            if($info->regular_pay == 3){
                $info->regular_pay_ext = MaintenanceSupplierPayShop::getShopList($id);
            }
            
            $info->credit_money = bcdiv($info->credit_money, 100, 2);   //授信额度 单位元
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'info' => $info,
                ]
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "getSupplierFinanceInfo", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-25 上午10:30
     * @Description:     根据供应商id获取供应商的公司、业务、财务信息相关
     * @param string $token             用户token
     * @param int $id                   供应商id
     * @link http://api.anhui.com/v1/pms/supplier/getSupplierInfo?token=3f0641ce3dc3ebb51ef49973fd5e1dd7&id=1
     */
    public function getSupplierInfo() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id = Input::get('id');                 //供应商id
            $select_arr = [
                'id', 'name', 'juridical', 'certify_type', 'certify_num', 'agent', 'postcode', 'operating_address', 
                'work_together_type', 'car_type', 'licence_name', 'licence_credit_num', 'licence_company_type', 
                'licence_juridical', 'licence_created_time', 'licence_home', 'licence_capital', 'licence_term_type', 
                'licence_term_starttime', 'licence_term_endtime', 'scope',
                'business_type', 'business_type_comment', 'business_rebate_policy', 'businss_express', 
                'after_sale', 'business_activity', 'business_train',
                'bank', 'account', 'regular_pay', 'invoice_type', 'invoice_address', 'billing_phone', 
                'taxpayer', 'gather_bank', 'gather_account', 'company_regist_address', 'regular_pay', 'regular_pay_comment', 
                'compare_bill', 'bill_day', 'credit_money', 'licence_credit_num', 'licence_home', 
                'supplier_class_level', 'logistics_freight', 'tax', 
            ];
            $info = MaintenanceSupplier::select($select_arr)
                    ->where('id', $id)
                    ->first();
            if(!$info){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            
            //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
            if($info->logistics_freight == 3){
                $info->logistics_freight_ext = MaintenanceSupplierLogisticsFreightArea::getAreaList($id);
            }
            if($info->logistics_freight == 4){
                $info->logistics_freight_ext = MaintenanceSupplierLogisticsFreightShop::getShopList($id);
            }
            //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
            if($info->regular_pay == 2){
                $info->regular_pay_ext = MaintenanceSupplierPayArea::getAreaList($id);
            }
            if($info->regular_pay == 3){
                $info->regular_pay_ext = MaintenanceSupplierPayShop::getShopList($id);
            }
            
            $info->credit_money = bcdiv($info->credit_money, 100, 2);   //授信额度 单位元
            //附件数组
            $files = [
                'gsjj' => [],   //公司简介
                'cpjs' => [],   //产品介绍
                'yyzzfyj' => [],   //营业执照复印件
                'frsfzfyj' => [],   //法人身份证复印件
                'ywxx' => [],   //业务信息
                'wlxx' => [],   //物流信息
                'shxx' => [],   //售后信息
                'scxx' => [],   //市场信息
                'pxxx' => [],   //培训信息
            ];
            //获取供应上的附件列表
            $files_list = PMSSupplierFiles::getFilesList($info->id);
            if(!empty($files_list)){
            $url = Config::get('config.pms_supplier_files_url');       //供应商附件目录
                foreach ($files_list as $k => $v) {
                    $temp = [
                        'id' => $v['id'],
                        'file_name' => $v['file_path'],
                        'storage_name' => $v['storage_name'],
                        'file_type' => $v['file_type'],
                        'file_url' => $url.''.$v['storage_name'],
                        'created_at' => $v['created_at'],
                        'created_by' => $v['created_by'],
                    ];
                    switch ($v['type']) {
                        case 'gsjj':
                            $files['gsjj'][] = $temp;
                            break;
                        case 'cpjs':
                            $files['cpjs'][] = $temp;
                            break;
                        case 'yyzzfyj':
                            $files['yyzzfyj'][] = $temp;
                            break;
                        case 'frsfzfyj':
                            $files['frsfzfyj'][] = $temp;
                            break;
                        case 'ywxx':
                            $files['ywxx'][] = $temp;
                            break;
                        case 'wlxx':
                            $files['wlxx'][] = $temp;
                            break;
                        case 'shxx':
                            $files['shxx'][] = $temp;
                            break;
                        case 'scxx':
                            $files['scxx'][] = $temp;
                            break;
                        case 'pxxx':
                            $files['pxxx'][] = $temp;
                            break;
                        default:
                            break;
                    }
                }
            }
            
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'info' => $info,
                    'files' => $files,
                ]
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "getSupplierInfo", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-25 下午2:11
     * @Description:     供应商上传附件相关
     * @param string $token             用户token
     * @param int $supplier_id          供应商id
     * @param string $type              附件类型 (gsjj:公司简介;cpjs:产品介绍;yyzzfyj:营业执照复印件;frsfzfyj:法人身份证复印件;
     * ywxx:业务i信息;wlxx:物流信息;shxx:售后信息;scxx:市场信息;pxxx:培训信息;htwb:合同文本;bcxy:补充协议;qtwb:其他文本;)
     * @param file $file                附件
     * @param int $contract_id          合同id (type类型为 合同文本、补充协议、其它文本 时， 合同id不能为空)
     * @param int $file_type            文件类型 (1:图片;2:非图片;)
     * @link http://api.anhui.com/v1/pms/supplier/supplierUploadFile?token=7b388e638f99e6e7364e70fc32c34258&supplier_id=1&type=htwb
     */
    public function supplierUploadFile() {
        header('Access-Control-Allow-Origin:*');
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'supplier_id' => 'required',
                //'name' => 'required',
                'type' => 'required',
                'file'=> 'required',   //最大上传2M
                'file_type'=> 'required',
                //type类型为 合同文本、补充协议、其它文本 时， 合同id不能为空
                'contract_id' => 'required_if:type,htwb|required_if:type,bcxy|required_if:type,qtfj',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $admin_id       = $res['user']->id;             //管理员id
            $supplier_id    = Input::get('supplier_id');    //供应商id
            //$name           = Input::get('name');           //上传传文件名称
            $type           = Input::get('type');           //类型
            $upload_file    = Input::file('file');          //上传文件
            $contract_id    = Input::get('contract_id', '');//合同id
            $file_type      = Input::get('file_type');      //文件类型 (1:图片;2:非图片;)
            if($upload_file->isValid()){
                //文件上传成功
                $name = $upload_file->getClientOriginalName();  //文件原名称
                //$extension = $upload_file->getClientOriginalExtension(); //扩展名
                $storage_name = date('Ymdhis', time()).'_'.$supplier_id.'_'.$name;               //存储名称
                $upload_file->move(Config::get('config.pms_supplier_files'), $storage_name);
            } else {
                $response = Lang::get("pms_error.supplier_file_error_30010");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $file = new PMSSupplierFiles();
            $file->supplier_id = $supplier_id;
            $file->type = $type;
            if($contract_id != ''){
                $file->contract_id = $contract_id;
            }
            $file->file_path = $name;
            $file->storage_name = $storage_name;
            $file->file_type = $file_type;
            $file->status = 1;
            $file->created_at = date('Y-m-d H:i:s', time());
            $file->created_by = $admin_id;
            try {
                $file->save();
                $model = 'supplierUploadFile';
                $supplier_id = $supplier_id;
                $type = 'new';
                $content = '用户：'.$admin_id.',上传文件';
                $old = null;
                $new = json_encode(PMSSupplierFiles::find($file->id));
                $by = $admin_id;
                PmsOpLog::write($model, $supplier_id, $type, $content, $old, $new, $by);
                
                if($contract_id != ''){
                    //添加合同操作记录日志
                    SupplierContractLog::writeContractLog($supplier_id, $contract_id, 3, $admin_id);
                }
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "supplierUploadFile", "input" =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
            
            $info = [
                'id' => $file->id,
                'file_name' => $file->file_path,
                'storage_name' => $file->storage_name,
                'file_type' => $file->file_type,
                'file_url' => Config::get('config.pms_supplier_files_url').''.$file->storage_name,
                'created_at' => $file->created_at,
                'created_by' => $file->created_by,
            ];
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'info' => $info,
                ]
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "supplierUploadFile", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-25 下午4:18
     * @Description:     供应商附件删除
     * @param string $token             用户token
     * @param int $id                   附件id
     * @link http://api.anhui.com/v1/pms/supplier/deleteSupplierFiles?token=60fccf4c8de5a9fc2f00d072cc89c941&id=1
     */
    public function deleteSupplierFiles() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id             = Input::get('id');                 //附件id
            $admin_id       = $res['user']->id;                 //管理员id
            $status         = 0;                                //删除状态
            
            $sf = PMSSupplierFiles::find($id);
            if(!$sf){
                $response = Lang::get("pms_error.supplier_file_not_exit_error_30011");
                break;
            }
            $old = clone $sf;
            $sf->status = $status;
            $sf->updated_at = date('Y-m-d H:i:s', time());
            $sf->updated_by = $admin_id;
            try{
                $sf->save();
                
                $model = 'deleteSupplierFiles';
                $supplier_id = $sf->supplier_id;
                $type = 'update';
                $content = '用户：'.$admin_id.',供应商删除附件，原状态：'.$old->status.',新状态：'.$status;
                $old = json_encode($old);
                $new = json_encode(PMSSupplierFiles::find($id));
                $by = $admin_id;
                PmsOpLog::write($model, $supplier_id, $type, $content, $old, $new, $by);
                
                if($sf->contract_id != ''){
                    //添加合同操作记录日志
                    SupplierContractLog::writeContractLog($supplier_id, $sf->contract_id, 4, $admin_id);
                }
                break;
            }catch (Exception $e) {
                Log::error("error", array("system" => "pms" ,"event" => "deleteSupplierFiles", "input" =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
            
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "deleteSupplierFiles", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-26 上午10:05
     * @Description:     添加(编辑)供应商合同信息
     * @param string $token             用户token
     * @param int $id                   合同id  (编辑时必传)
     * @param int $supplier_id          供应商id
     * @param string $name              合同中的公司名称
     * @param int $type                 合同类型 (1:配件;2:商品;3:设备;4:维修服务;)
     * @param int $delay_status         是否延期  (1:无需延期;2:已延期;3:到期不延期;)
     * @param date $sign_date           签订日期
     * @param date $over_date           中止日期
     * @param string $comment           合同备注信息
     * @link http://api.anhui.com/v1/pms/supplier/addContractInfo?token=a7a66284fbbfba4380a09049b93213cb
     * @link http://api.anhui.com/v1/pms/supplier/addContractInfo?token=a7a66284fbbfba4380a09049b93213cb&supplier_id=1&name=测试&type=1&delay_status=1&sign_date=2018-06-26&over_date=2018-07-26&comment=备注说明
     */
    public function addContractInfo() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'supplier_id' => 'required',
                'name' => 'required',
                'type' => 'required',
                'delay_status' => 'required',
                'sign_date' => 'required',
                'over_date' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id             = Input::get('id', '');         //合同id
            $supplier_id    = Input::get('supplier_id');    //供应商id
            $name           = Input::get('name');           //合同中的公司名称
            $type           = Input::get('type');           //合同类型 (1:配件;2:商品;3:设备;4:维修服务;)
            $delay_status   = Input::get('delay_status');   //是否延期  (1:无需延期;2:已延期;3:到期不延期;)
            $sign_date      = Input::get('sign_date');      //签订日期
            $over_date      = Input::get('over_date');      //终止日期
            $comment        = Input::get('comment', '');    //合同备注信息
            $admin_id       = $res['user']->id;             //管理员id
            
            if($id != ''){
                $sc = SupplierContract::find($id);
                if(!$sc){
                    $response = Lang::get("pms_error.supplier_contract_error_30013");
                    break;
                }
                $sc->updated_at = date('Y-m-d H:i:s', time());
                //操作类型 (1:新建合同;2:编辑合同;3:上传附件;4:删除附件;)
                $action_type = 2;
            } else {
                $sc = new SupplierContract();
                $sc->created_at = date('Y-m-d H:i:s', time());
                $action_type = 1;
            }
            
            $sc->supplier_id = $supplier_id;
            $sc->name = $name;
            $sc->type = $type;
            $sc->delay_status = $delay_status;
            $sc->sign_date = $sign_date;
            $sc->over_date = $over_date;
            if($comment != ''){
                $sc->comment = $comment;
            }
            
            try{
                $res = $sc->save();
                if($res){
                    //同步供应商合同状态
                    SupplierContract::supplierContractStatus($supplier_id);
                    //添加合同操作记录日志
                    SupplierContractLog::writeContractLog($supplier_id, $sc->id, $action_type, $admin_id);
                }
            }catch (Exception $e) {
                Log::error("error", array("system" => "pms" ,"event" => "addContractInfo", "input" =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_contract_add_error_30012");
                break;
            }
            $info = [
                'id' => $sc->id,    //合同id
            ];
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'info' => $info,
                ]
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "addContractInfo", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-26 下午5:55
     * @Description:     编辑供应商合同信息
     * @param string $token             用户token
     * @param int $id                   合同id
     * @param int $supplier_id          供应商id
     * @param string $name              合同中的公司名称
     * @param int $type                 合同类型 (1:配件;2:商品;3:设备;4:维修服务;)
     * @param int $delay_status         是否延期  (1:无需延期;2:已延期;3:到期不延期;)
     * @param date $sign_date           签订日期
     * @param date $over_date           中止日期
     * @param string $comment           合同备注信息
     * @link http://api.anhui.com/v1/pms/supplier/modifyContractInfo?token=a7a66284fbbfba4380a09049b93213cb
     * @link http://api.anhui.com/v1/pms/supplier/modifyContractInfo?token=a7a66284fbbfba4380a09049b93213cb&id=1&supplier_id=1&name=测试&type=1&delay_status=1&sign_date=2018-06-26&over_date=2018-07-26&comment=备注说明
     */
    public function modifyContractInfo() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'supplier_id' => 'required',
                'name' => 'required',
                'type' => 'required',
                'delay_status' => 'required',
                'sign_date' => 'required',
                'over_date' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id             = Input::get('id');             //合同id
            $supplier_id    = Input::get('supplier_id');    //供应商id
            $name           = Input::get('name');           //合同中的公司名称
            $type           = Input::get('type');           //合同类型 (1:配件;2:商品;3:设备;4:维修服务;)
            $delay_status   = Input::get('delay_status');   //是否延期  (1:无需延期;2:已延期;3:到期不延期;)
            $sign_date      = Input::get('sign_date');      //签订日期
            $over_date      = Input::get('over_date');      //终止日期
            $comment        = Input::get('comment', '');    //合同备注信息
            $admin_id       = $res['user']->id;             //管理员id
            
            $sc = SupplierContract::find($id);
            if(!$sc){
                $response = Lang::get("pms_error.supplier_contract_error_30013");
                break;
            }
            $sc->supplier_id = $supplier_id;
            $sc->name = $name;
            $sc->type = $type;
            $sc->delay_status = $delay_status;
            $sc->sign_date = $sign_date;
            $sc->over_date = $over_date;
            if($comment != ''){
                $sc->comment = $comment;
            }
            $sc->updated_at = date('Y-m-d H:i:s', time());
            
            try{
                $res = $sc->save();
                if($res){
                    //同步供应商合同状态
                    SupplierContract::supplierContractStatus($supplier_id);
                    //添加合同操作记录日志
                    SupplierContractLog::writeContractLog($supplier_id, $sc->id, 2, $admin_id);
                }
            }catch (Exception $e) {
                Log::error("error", array("system" => "pms" ,"event" => "modifyContractInfo", "input" =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_contract_add_error_30012");
                break;
            }
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "modifyContractInfo", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-26 下午1:21
     * @Description:     供应商合同列表
     * @param string $token             用户token
     * @param int $supplier_id          供应商id
     * @param int $page                 页码 [ 默认为1 ]
     * @param int $page_size            每页数据条数 [ 默认为25 ]
     * @link http://api.anhui.com/v1/pms/supplier/contractList?token=60fccf4c8de5a9fc2f00d072cc89c941&supplier_id=1
     */
    public function contractList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'supplier_id' => 'required',
                'page' => 'integer',
                'page_size' => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $supplier_id        = Input::get('supplier_id');            //供应商id
            $page               = Input::get('page', 1);                //页码 [ 默认为1 ]
            $page_size          = Input::get('page_size', 25);          //每页数据条数 [ 默认为25 ]
            
            $select_arr = [
                'id', 'supplier_id', 'name', 'type', 'delay_status', 'sign_date', 'over_date', 'contract_status', 'comment',
            ];
            $list = SupplierContract::select($select_arr)
                    ->where('supplier_id', $supplier_id)
                    ->orderBy('created_at', 'desc');
            $count = $list->count();
            $list = $list->skip($page_size*($page-1))->take($page_size)->get();
            
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'count' => $count,
                    'list' => $list,
                ],
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "contractList", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-26 下午3:09
     * @Description:     供应商合同附件列表
     * @param string $token             用户token
     * @param int $supplier_id          供应商id
     * @param int $contract_id          合同id
     * @link http://api.anhui.com/v1/pms/supplier/contractFilesList?token=a7a66284fbbfba4380a09049b93213cb&supplier_id=1&contract_id=1
     */
    public function contractFilesList() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'supplier_id' => 'required',
                'contract_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $supplier_id = Input::get('supplier_id');                 //供应商id
            $contract_id = Input::get('contract_id');                 //合同id
            
            //附件数组
            $files = [
                'htwb' => [],   //合同文本
                'bcxy' => [],   //补充协议
                'qtwb' => [],   //其他文本
            ];
            //获取供应上的附件列表
            $files_list = PMSSupplierFiles::getFilesList($supplier_id, $contract_id);
            if(!empty($files_list)){
                $url = Config::get('config.pms_supplier_files_url');       //供应商附件目录
                foreach ($files_list as $k => $v) {
                    $temp = [
                        'id' => $v['id'],
                        'file_name' => $v['file_path'],
                        'storage_name' => $v['storage_name'],
                        'file_type' => $v['file_type'],
                        'file_url' => $url.''.$v['storage_name'],
                        'created_at' => $v['created_at'],
                        'created_by' => $v['created_by'],
                    ];
                    switch ($v['type']) {
                        case 'htwb':
                            $files['htwb'][] = $temp;
                            break;
                        case 'bcxy':
                            $files['bcxy'][] = $temp;
                            break;
                        case 'qtwb':
                            $files['qtwb'][] = $temp;
                            break;
                        default:
                            break;
                    }
                }
            }
            
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'files' => $files,
                ]
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "contractFilesList", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-6-26 下午4:25
     * @Description:     供应商合同操作记录列表
     * @param string $token             用户token
     * @param int $supplier_id          供应商id
     * @param int $contract_id          合同id
     * @param string $op_date_start     操作起始日期
     * @param string $op_date_end       操作结束日期
     * @link http://api.anhui.com/v1/pms/supplier/contractLogList?token=60fccf4c8de5a9fc2f00d072cc89c941&supplier_id=1&contract_id=1
     */
    public function contractLogList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'supplier_id' => 'required',
                'contract_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $supplier_id    = Input::get('supplier_id');            //供应商id
            $contract_id    = Input::get('contract_id');            //合同id
            $op_date_start  = Input::get('op_date_start', '');      //操作起始日期
            $op_date_end    = Input::get('op_date_end', '');        //操作结束日期
            
            $select_arr = [
                'supplier_contract_logs.id', 'supplier_contract_logs.supplier_id', 'supplier_contract_logs.contract_id', 
                'supplier_contract_logs.action_type', 'supplier_contract_logs.created_at', 'supplier_contract_logs.created_by',
                'pms_user.real_name', 
            ];
            $list = SupplierContractLog::leftJoin('pms_user', 'supplier_contract_logs.created_by', '=', 'pms_user.id')
                    ->select($select_arr)
                    ->where('supplier_contract_logs.supplier_id', $supplier_id)
                    ->where('supplier_contract_logs.contract_id', $contract_id)
                    ->orderBy('supplier_contract_logs.created_at', 'desc');
            if($op_date_start != ''){
                $list->where('supplier_contract_logs.created_at', '>=', $op_date_start.' 00:00:00');
            }
            if($op_date_end != ''){
                $list->where('supplier_contract_logs.created_at', '<=', $op_date_end.' 23:59:59');
            }
            $list = $list->get();
            
            $response = [
                'code' => 0, 
                'msg' => 'ok',
                'result' => [
                    'list' => $list,
                ],
            ];
        }while(false);
        
        Log::info("info", array("system" => "pms" ,"event" => "contractLogList", "input" =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-9-13 上午10:01
     * @Description:     获取门店所在城市列表
     * @param string $token             用户token
     * @link http://api.anhui.com/v1/pms/supplier/getCityList?token=66cc793e680277ab0cbda28ad949d546
     */
    public function getCityList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
//            $select_arr = [
//                'resource_city.id AS city_id', 'resource_city.city_name',
//            ];
//            $city_list = MaintenanceShops::leftJoin('anhui_data.resource_city', 'maintenance_shops.city_id', '=', 'resource_city.id')
//                    ->where('maintenance_shops.status', 1)
//                    ->groupBy('maintenance_shops.city_id')
//                    ->select($select_arr)
//                    ->get()
//                    ->toArray();
            $select_arr = [
                'id AS city_id', 'name AS city_name',
            ];
            $city_list = ResourceCityType::where('status', 1)
                    ->select($select_arr)
                    ->orderBy('id')
                    ->get()
                    ->toArray();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['city_list' => $city_list]);
        }while(false);
            Log::info("info", array("system" => "pms", "event" => "supplier/getCityList", "input" => Input::all(), "output" => $response));
            return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-9-13 上午11:19
     * @Description:     获取门店列表 (可以根据城市进行搜索)
     * @param string $token             用户token
     * @param int $city_id              供应商id
     * @link http://api.anhui.com/v1/pms/supplier/getShopList?token=66cc793e680277ab0cbda28ad949d546&city_id=1
     */
    public function getShopList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $city_id = Input::get('city_id', '');
            $select_arr = [
                'id', 'name', 'city_id',
            ];
            $shop_list = MaintenanceShops::where('status', 1)
                    ->select($select_arr);
            if($city_id != ''){
                $shop_list->where('city_id', $city_id);
            }
            $shop_list = $shop_list->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['shop_list' => $shop_list]);
        }while(false);
            Log::info("info", array("system" => "pms", "event" => "supplier/getShopList", "input" => Input::all(), "output" => $response));
            return json_encode($response);
    }
    
    
}